package com.wdxy.annotation.dao;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Test {
	
	public static void main(String[] args) {
		Filter f1 = new Filter();
		Filter f2 = new Filter();
		Filter f3 = new Filter();
		//f1.setAge(3);
		f2.setUserName("liwen");
		f3.setEmail("java@qq.com,livescript@qq.com,python@qq.com");
		
		String sql1 = query(f1);
		System.out.println(sql1);
		
		String sql2 = query(f2);
		System.out.println(sql2);
		
		String sql3 = query(f3);
		System.out.println(sql3);
		
	}
	
	@SuppressWarnings("unchecked")
	public static String query(Filter f){
		
		//1.获取数据库表名
		@SuppressWarnings("rawtypes")
		Class c = f.getClass();
		boolean exist = c.isAnnotationPresent(Table.class);
		if(!exist){
			return "数据库表名不存在";
		}
		Table t = (Table) c.getAnnotation(Table.class);
		String tableName = t.value();
		StringBuilder sb= new StringBuilder();
		sb.append("select * from ").append(tableName).append(" where 1=1 ");
		Field[] fs = c.getDeclaredFields();//c.getFields()获取public
		for(Field fd:fs){
			boolean fExist = fd.isAnnotationPresent(Column.class);
			if(!fExist){
				continue;
			}
			
			//2.获取字段名
			Column cn = fd.getAnnotation(Column.class);
			String columnName = cn.value();
			//3.获取字段值,反射
			//Method[] mds = c.getMethods();
			String fieldName = fd.getName();
			String getMethod = "get"+fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1);
			Object fieldValue = "";
			try {
				Method getValue = c.getMethod(getMethod);
				fieldValue = getValue.invoke(f);
				if(fieldValue!=null){
					sb.append(" and ").append(columnName).append(" = ").append(fieldValue);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		return sb.toString();
	}
}
